<script setup lang="ts">
import { frequencyType, shareType, shareCycleType } from "@/config/dictionary";
import { zoonType } from "../components/config";
import { deepClone } from "@/utils";
import PrizePool from "./PrizePool.vue";
import RewardSelector from "./RewardSelector.vue";

const props = defineProps({
  modelValue: {
    type: Object,
    required: true,
  },
});

const emits = defineEmits(["change", "update:modelValue"]),
  currencyList: any = inject("currencyList", []),
  activityBaseInfo: any = inject("activityBaseInfo", {}),
  activityReadonly = inject("activityReadonly", false);

const form = ref<any>({
    partType: 0,
    freeType: 4,
    partTotalLimit: 0,
    lotteryTotalLimit: 0,
    lotteryLimitType: 0,
  }),
  prizeAreas = ref<Array<any>>([]),
  shareConfig = ref<any>({
    lotteryConfig: 0,
    shareType: 4,
    shareNum: 1,
    shareCycle: 4,
    repeatLimit: 0,
    repeatCycle: 1,
    repeatNum: 1,
    inviteLimit: 1,
    inviteNum: 1,
    rewardList: [{ rewardNum: 1 }],
  });

const formRef = ref(),
  poolRef = ref(),
  shareRef = ref();

const rules = {
  lotteryTotalNum: [
    { required: true, message: "请输入中奖总次数", trigger: "blur" },
  ],
  shareType: [{ required: true, message: "请选择裂变方式", trigger: "change" }],
  shareNum: [{ required: true, message: "请填写邀请人数", trigger: "blur" }],
  inviteCycle: [
    { required: true, message: "请选择邀请周期", trigger: "change" },
  ],
};

const prizePoolType = computed(() => {
  return form.value.subType ? zoonType[form.value.subType].prizePool || [] : [];
});

const limitsDisabled = computed(() => {
  return form.value.hasTicket == 1 && activityBaseInfo.value.status == 2;
});

const stopWatch = watch(
  () => props.modelValue,
  (val) => {
    nextTick(() => {
      stopWatch();
      formatData(val);
    });
  },
  {
    immediate: true,
  }
);

const formatData = (val: any) => {
  form.value = Object.assign({}, form.value, {
    ...val.pageArea,
    lotteryLimit:
      val.pageArea.lotteryLimit && typeof val.pageArea.lotteryLimit === "string"
        ? JSON.parse(val.pageArea.lotteryLimit)
        : [{ type: 1, limitNum: 1 }],
    lotteryLimitType: val.pageArea.lotteryLimit ? 1 : 0,
    partLimit: null,
  });

  if (val.actShareConfig) {
    shareConfig.value = val.actShareConfig;
  } else {
    shareConfig.value = Object.assign({}, shareConfig.value, {
      pageArea: form.value.pageFlag,
      pureShare: form.value.subType == "TeamUp" ? 1 : 0,
    });
    initShareConfig();
  }
  prizeAreas.value = val.prizeAreas || [];
  updateData();
};

// 初始化表单项
const initShareConfig = () => {
  if (form.value.subType == "TeamUp") {
    shareConfig.value.rewardImmediate = 0;
    shareConfig.value.mediatePageArea = form.value.pageArea;
  } else {
    // 抽奖裂变固定给抽奖机会
    shareConfig.value.rewardImmediate = 0;
    shareConfig.value.mediatePageArea = form.value.pageArea;
  }
};

const showPrizePool = computed(() => {
  // 开启抽奖，展示抽奖配置
  if (shareConfig.value.lotteryConfig == 1) {
    return true;
  }
  return false;
});

const quotePrize = computed(() => {
  let prize = (shareConfig.value.rewardList || []).filter((item: any) => {
    if (item.rewardType === "PRIZE") {
      return true;
    }
    return false;
  });
  if (prize && prize.length > 0) {
    return prize.map((item: any) => {
      return {
        prizeId: item.prizeId,
        poolId: item.prizeArea,
        specId: item.prizeSpec,
      };
    });
  }
  return [];
});

// 切换是否开启抽奖
const onChangeLotteryConfig = () => {
  if (shareConfig.value.lotteryConfig == 0) {
    shareConfig.value.rewardList.forEach((item: any) => {
      if (item.rewardEntity.rewardType === "LOTTERY") {
        item.rewardEntity.rewardType = "";
        item.rewardEntity.lotteryArea = "";
        item.rewardEntity.lotteryAreaUid = "";
      }
    });
  }
  updateData();
};

const onChangeShareNum = () => {
  updateData();
};

// 添加奖池
const addPool = () => {
  poolRef.value.addPool();
};

// 添加奖池奖品
const addPoolPrize = (index: number) => {
  poolRef.value.addPrize(1, index);
};

const updateData = () => {
  emits("update:modelValue", {
    pageArea: form.value,
    prizeAreas: prizeAreas.value,
    actShareConfig: shareConfig.value,
  });
  emits("change");
};

const submit = () => {
  return new Promise((resolve, reject) => {
    formRef.value.validate(async (valid: any, invalidFields: any) => {
      if (valid) {
        let detail: any = deepClone(form.value);
        let actShareConfig = {};
        // 每人中奖限制
        if (detail.lotteryLimitType == 0) {
          detail.lotteryLimit = "";
        } else if (detail.lotteryLimit)
          detail.lotteryLimit = JSON.stringify(detail.lotteryLimit);

        detail.freeNum = null;
        detail.freeType = null;

        try {
          actShareConfig = await checkShare();
          await poolRef.value.check(
            detail.lotteryLimitType === 1 || detail.lotteryTotalLimit === 1,
            true
          );
        } catch (e) {
          reject(e);
        }

        resolve({
          pageArea: detail,
          prizeAreas: prizeAreas.value,
          actShareConfig: actShareConfig,
        });
      } else {
        formRef.value.scrollToField(Object.keys(invalidFields)[0]);
        reject(`请检查${form.value.name}`);
      }
    });
  });
};

// 分享参数校验
const checkShare = (): any => {
  return new Promise((resolve, reject) => {
    shareRef.value.validate(async (valid: any) => {
      if (valid) {
        let detail: any = deepClone(shareConfig.value);
        detail.rewardList.forEach((reward: any) => {
          if (reward.lotteryAreaUid) reward.lotteryArea = "";
          if (reward.prizeAreaUid) reward.prizeArea = "";
          if (reward.prizeUid) reward.prizeId = "";
          if (reward.prizeSpecUid) reward.prizeSpec = "";
          if (reward.ticketAct === "local") reward.ticketAct = "";
        });

        // 抽奖裂变 (计算邀请轮次)
        if (form.value.subType !== "TeamUp") {
          detail.inviteNum = parseInt(
            Number(
              shareConfig.value.inviteNum / shareConfig.value.shareNum
            ).toString()
          );
        } else {
          detail.inviteCycle = detail.shareCycle;
        }
        resolve(detail);
      } else reject(`请检查${form.value.name}`);
    });
  });
};

defineExpose({ submit, refresh: formatData });
</script>
<template>
  <el-form
    ref="formRef"
    :model="form"
    :rules="rules"
    :disabled="activityReadonly"
    label-width="auto"
  >
    <!-- 中奖限制 -->
    <template v-if="showPrizePool">
      <h3 class="collpase-title">中奖限制</h3>
      <el-form-item label="中奖总次数：" prop="lotteryTotalLimit">
        <el-radio-group v-model="form.lotteryTotalLimit">
          <el-radio :label="0">不限</el-radio>
          <el-radio :label="1">限制</el-radio>
        </el-radio-group>
        <template v-if="form.lotteryTotalLimit == 1">
          <el-form-item label-width="10px" prop="lotteryTotalNum">
            <EasyNumberInput
              v-model="form.lotteryTotalNum"
              :min="1"
              :max="9999"
              :precision="0"
              unit="次"
            />
          </el-form-item>
        </template>
      </el-form-item>
      <el-form-item label="中奖次数：">
        <el-radio-group v-model="form.lotteryLimitType">
          <el-radio :label="0">不限</el-radio>
          <el-radio :label="1">限制</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item v-if="form.lotteryLimitType == 1">
        <div class="flex-contain" v-for="(limit, index) in form.lotteryLimit">
          每人&nbsp;&nbsp;
          <el-select
            v-model="limit.type"
            placeholder="请选择"
            style="width: 100px"
          >
            <el-option
              v-for="(item, key) in frequencyType"
              :label="item"
              :value="Number(key)"
            /> </el-select
          >&nbsp;&nbsp; 最多
          <el-form-item
            label-width="10px"
            :prop="`lotteryLimit.${index}.limitNum`"
            :rules="[
              { required: true, message: '请填写限制次数', trigger: 'blur' },
            ]"
          >
            <EasyNumberInput
              v-model="limit.limitNum"
              :min="1"
              :max="9999"
              unit="次"
              :precision="0"
            ></EasyNumberInput>
          </el-form-item>
        </div>
      </el-form-item>
    </template>
  </el-form>
  <el-form
    ref="shareRef"
    :model="shareConfig"
    :rules="rules"
    label-width="auto"
    :disabled="activityReadonly"
  >
    <h3 class="collpase-title">裂变配置</h3>
    <el-form-item label="配置抽奖：">
      <el-switch
        v-model="shareConfig.lotteryConfig"
        inline-prompt
        active-text="是"
        inactive-text="否"
        :active-value="1"
        :inactive-value="0"
        :disabled="limitsDisabled"
        @change="onChangeLotteryConfig"
      />
    </el-form-item>
    <el-form-item label="裂变方式：">
      <el-form-item label-width="0" prop="shareType">
        <el-select
          v-model="shareConfig.shareType"
          placeholder="请选择裂变方式"
          :disabled="limitsDisabled"
          style="width: 250px"
        >
          <el-option
            v-for="(item, key) in shareType"
            :label="item"
            :value="Number(key)"
          />
        </el-select>
      </el-form-item>
    </el-form-item>
    <el-form-item label="裂变奖励：">
      每邀请<el-form-item label-width="10px" prop="shareNum">
        <EasyNumberInput
          v-model="shareConfig.shareNum"
          :min="1"
          :max="10"
          unit="人"
          :precision="0"
          @change="onChangeShareNum"
          style="width: 150px"
        /> </el-form-item
      >&nbsp;&nbsp;获得
      <template v-for="(reward, rIndex) in shareConfig.rewardList">
        <RewardSelector
          v-model="shareConfig.rewardList[rIndex]"
          :subType="form.subType"
          :lottery="shareConfig.lotteryConfig == 1 ? true : false"
          :prizeAreas="prizeAreas"
          :prefix="`rewardList.${rIndex}.`"
          @change="updateData"
          @addPool="addPool"
          @addPrize="addPoolPrize"
        />
      </template>
    </el-form-item>
    <!-- 组队裂变 -->
    <el-form-item
      v-if="form.subType == 'TeamUp'"
      label="分享周期："
      prop="shareCycle"
    >
      <el-select
        v-model="shareConfig.shareCycle"
        placeholder="请选择"
        :disabled="limitsDisabled"
      >
        <el-option
          v-for="(item, key) in shareCycleType"
          :label="item"
          :value="Number(key)"
        />
      </el-select>
    </el-form-item>
    <!-- 抽奖裂变 -->
    <el-form-item v-else>
      每人
      <el-form-item label-width="10px" prop="inviteCycle">
        <el-select
          v-model="shareConfig.inviteCycle"
          placeholder="请选择"
          :disabled="limitsDisabled"
          style="width: 100px"
        >
          <el-option
            v-for="(item, key) in shareCycleType"
            :label="item"
            :value="Number(key)"
          />
        </el-select>
      </el-form-item>
      &nbsp;&nbsp;最多可邀请
      <el-form-item label-width="10px" prop="inviteNum">
        <EasyNumberInput
          v-model="shareConfig.inviteNum"
          :min="1"
          unit="人"
          placeholder="请输入邀请人数"
          :precision="0"
          :disabled="limitsDisabled"
          style="width: 150px"
        />
      </el-form-item>
    </el-form-item>
    <template v-if="shareConfig.shareType == 2">
      <el-form-item prop="repeatLimit">
        <template #label>
          <span>重复邀请限制：</span>
          <el-tooltip effect="dark" placement="top">
            <template #content>
              <div>
                1、不限：每位用户助力次数不限，且只能给同一个人助力1次（不能给自己助力）<br />
                2、限制：每位用户助力次数有限，且只能给同一个人助力1次（不能给自己助力）
              </div>
            </template>
            <el-icon style="margin-top: 8px; cursor: pointer"
              ><InfoFilled
            /></el-icon>
          </el-tooltip>
        </template>
        <el-radio-group v-model="shareConfig.repeatLimit">
          <el-radio :label="0">不限</el-radio>
          <el-radio :label="1">限制</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item v-if="shareConfig.repeatLimit == 1">
        <el-form-item label-width="0" prop="repeatCycle">
          <el-select
            v-model="shareConfig.repeatCycle"
            placeholder="请选择"
            style="width: 100px"
          >
            <el-option label="活动期间" :value="4" />
            <el-option label="每月" :value="3" />
            <el-option label="每周" :value="2" />
            <el-option label="每日" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label-width="10px" prop="repeatNum">
          <EasyNumberInput
            v-model="shareConfig.repeatNum"
            :min="1"
            unit="次"
            placeholder="请输入奖励数量"
            :precision="0"
            style="width: 150px"
          />
        </el-form-item>
      </el-form-item>
    </template>
  </el-form>
  <PrizePool
    ref="poolRef"
    v-model="prizeAreas"
    :poolType="showPrizePool ? [1, 2] : [2]"
    :poolBaseInfo="prizePoolType"
    :pageFlag="form.pageFlag"
    :quote="quotePrize"
    @change="updateData"
  ></PrizePool>
</template>
<style lang="scss" scoped>
.collpase-title {
  position: relative;
  padding-left: 10px;
  font-size: 16px;
  margin-bottom: 10px;
  &::before {
    content: "";
    display: block;
    width: 3px;
    height: 16px;
    border-radius: 2px;
    background-color: var(--el-color-primary);
    position: absolute;
    left: 0;
    top: 50%;
    transform: translateY(-50%);
  }
  span {
    font-size: 13px;
    color: #909399;
    margin-left: 10px;
    font-weight: normal;
  }
}

.flex-contain {
  display: flex;
  flex-wrap: wrap;
  width: 100%;
}
</style>
